package com.example.backend.config;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.Role;
import com.example.backend.domain.enums.TicketPriority;
import com.example.backend.domain.enums.TicketSource;
import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.repository.TicketRepository;
import com.example.backend.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Configuration
public class TicketDataSeeder {
    
    private static final Random random = new Random();
    
    @Bean
    @Transactional
    public CommandLineRunner initTicketData(
            TicketRepository ticketRepository, 
            UserRepository userRepository) {
        return args -> {
            // 检查是否已有工单数据
            if (ticketRepository.count() > 0) {
                System.out.println("数据库已有工单数据，跳过示例数据生成");
                return;
            }
            
            System.out.println("开始生成示例工单数据...");
            
            // 获取现有的用户
            List<User> agents = userRepository.findByRole(Role.AGENT, Pageable.unpaged()).getContent();
            List<User> customers = userRepository.findByRole(Role.CUSTOMER, Pageable.unpaged()).getContent();
            List<User> admins = userRepository.findByRole(Role.ADMIN, Pageable.unpaged()).getContent();
            
            if (agents.isEmpty() || customers.isEmpty()) {
                System.out.println("⚠️ 缺少必要的用户数据，请先运行用户初始化");
                return;
            }
            
            // 生成40个示例工单
            int ticketCount = 0;
            Instant now = Instant.now();
            
            // 定义示例工单数据
            List<SampleTicketData> sampleTickets = Arrays.asList(
                // ========== 新建状态 (OPEN) - 5个 ==========
                new SampleTicketData("系统登录失败", "无法使用用户名密码登录系统，一直提示密码错误", TicketStatus.OPEN, TicketPriority.HIGH, -1, 3),
                new SampleTicketData("忘记密码", "登录时忘记了账号密码，需要重置密码", TicketStatus.OPEN, TicketPriority.MEDIUM, -2, 5),
                new SampleTicketData("账号被锁定", "多次输入错误密码后账号被锁定，无法登录", TicketStatus.OPEN, TicketPriority.MEDIUM, -3, 7),
                new SampleTicketData("注册流程问题", "在注册新账号时遇到验证码无法显示的问题", TicketStatus.OPEN, TicketPriority.LOW, -4, 2),
                new SampleTicketData("资料修改", "需要修改个人资料信息，但保存后没有生效", TicketStatus.OPEN, TicketPriority.LOW, -5, 4),
                
                // ========== 待处理状态 (OPEN) - 8个 ==========
                new SampleTicketData("订单支付失败", "下单后支付过程中提示支付失败，但钱已被扣除", TicketStatus.OPEN, TicketPriority.URGENT, -6, 1),
                new SampleTicketData("商品无法退款", "申请退款后3天仍未到账，联系客服无回应", TicketStatus.OPEN, TicketPriority.HIGH, -8, 6),
                new SampleTicketData("物流信息异常", "订单显示已发货，但物流信息一直未更新", TicketStatus.OPEN, TicketPriority.MEDIUM, -10, 8),
                new SampleTicketData("发票申请问题", "申请开具发票后一直处于审核状态，没有进展", TicketStatus.OPEN, TicketPriority.MEDIUM, -12, 9),
                new SampleTicketData("优惠券无法使用", "领取的优惠券显示可用，但结账时无法使用", TicketStatus.OPEN, TicketPriority.MEDIUM, -14, 5),
                new SampleTicketData("积分查询异常", "会员积分与实际消费不符，查询记录异常", TicketStatus.OPEN, TicketPriority.LOW, -16, 7),
                new SampleTicketData("系统响应慢", "打开页面需要等待30秒以上，严重影响使用体验", TicketStatus.OPEN, TicketPriority.MEDIUM, -18, 10),
                new SampleTicketData("数据丢失", "昨天保存的重要数据今天查看时发现丢失了", TicketStatus.OPEN, TicketPriority.HIGH, -20, 11),
                
                // ========== 处理中状态 (IN_PROGRESS) - 6个 ==========
                new SampleTicketData("账户余额不对", "账户余额显示不正确，交易记录也有异常", TicketStatus.IN_PROGRESS, TicketPriority.URGENT, -2, 1),
                new SampleTicketData("VIP权限异常", "开通VIP会员后，VIP特权无法正常使用", TicketStatus.IN_PROGRESS, TicketPriority.HIGH, -3, 4),
                new SampleTicketData("消息推送重复", "收到多条重复的消息推送，影响正常使用", TicketStatus.IN_PROGRESS, TicketPriority.MEDIUM, -5, 6),
                new SampleTicketData("跨平台同步", "手机和电脑数据不同步，修改一个平台另一个不更新", TicketStatus.IN_PROGRESS, TicketPriority.MEDIUM, -7, 8),
                new SampleTicketData("推荐算法问题", "推荐的内容不符合个人偏好，多次反馈无改善", TicketStatus.IN_PROGRESS, TicketPriority.LOW, -9, 2),
                new SampleTicketData("广告弹窗太多", "应用内广告弹出过于频繁，影响正常浏览", TicketStatus.IN_PROGRESS, TicketPriority.LOW, -11, 7),
                
                // ========== 待确认状态 (IN_PROGRESS) - 3个 ==========
                new SampleTicketData("功能需求建议", "建议增加批量操作功能，提高工作效率", TicketStatus.IN_PROGRESS, TicketPriority.MEDIUM, -1, 3),
                new SampleTicketData("界面优化建议", "建议优化界面布局，使其更加用户友好", TicketStatus.IN_PROGRESS, TicketPriority.LOW, -2, 5),
                new SampleTicketData("数据导出功能", "需要增加数据导出为Excel的功能", TicketStatus.IN_PROGRESS, TicketPriority.MEDIUM, -3, 9),
                
                // ========== 已解决状态 (RESOLVED) - 10个 ==========
                new SampleTicketData("邮箱验证问题", "注册时邮箱验证邮件收不到", TicketStatus.RESOLVED, TicketPriority.HIGH, -7, 2, -2),
                new SampleTicketData("短信验证码延迟", "短信验证码发送时间过长，超过5分钟才收到", TicketStatus.RESOLVED, TicketPriority.MEDIUM, -10, 4, -4),
                new SampleTicketData("浏览器兼容性", "使用Chrome浏览器时页面显示异常", TicketStatus.RESOLVED, TicketPriority.MEDIUM, -14, 6, -5),
                new SampleTicketData("文件上传失败", "上传文件时提示服务器错误", TicketStatus.RESOLVED, TicketPriority.HIGH, -18, 8, -6),
                new SampleTicketData("权限访问问题", "某些功能提示没有访问权限", TicketStatus.RESOLVED, TicketPriority.MEDIUM, -22, 10, -7),
                new SampleTicketData("搜索结果错误", "搜索功能返回的结果不准确", TicketStatus.RESOLVED, TicketPriority.LOW, -25, 3, -8),
                new SampleTicketData("通知设置失效", "关闭通知后仍然收到大量推送", TicketStatus.RESOLVED, TicketPriority.LOW, -30, 5, -9),
                new SampleTicketData("切换语言问题", "切换语言后界面没有完全切换", TicketStatus.RESOLVED, TicketPriority.LOW, -35, 7, -10),
                new SampleTicketData("夜间模式异常", "开启夜间模式后部分区域显示异常", TicketStatus.RESOLVED, TicketPriority.LOW, -40, 11, -11),
                new SampleTicketData("字体大小问题", "无法调整字体大小，默认字体太小", TicketStatus.RESOLVED, TicketPriority.LOW, -45, 1, -12),
                
                // ========== 已关闭状态 (CLOSED) - 8个 ==========
                new SampleTicketData("密码强度提示", "建议增加密码强度实时提示功能", TicketStatus.CLOSED, TicketPriority.LOW, -5, 2, -3),
                new SampleTicketData("安全设置优化", "建议增加更多安全验证选项", TicketStatus.CLOSED, TicketPriority.LOW, -8, 4, -4),
                new SampleTicketData("性能优化建议", "系统在某些场景下运行速度较慢", TicketStatus.CLOSED, TicketPriority.MEDIUM, -12, 6, -5),
                new SampleTicketData("文档更新请求", "用户手册内容过时，需要更新", TicketStatus.CLOSED, TicketPriority.LOW, -16, 8, -6),
                new SampleTicketData("多语言支持", "建议支持更多语言", TicketStatus.CLOSED, TicketPriority.LOW, -20, 10, -7),
                new SampleTicketData("移动端适配", "移动端界面有待改进", TicketStatus.CLOSED, TicketPriority.MEDIUM, -25, 1, -8),
                new SampleTicketData("API接口文档", "需要提供完整的API接口文档", TicketStatus.CLOSED, TicketPriority.MEDIUM, -30, 3, -9),
                new SampleTicketData("客服响应优化", "建议优化客服响应速度", TicketStatus.CLOSED, TicketPriority.LOW, -35, 5, -10)
            );
            
            // 创建工单
            for (SampleTicketData sampleData : sampleTickets) {
                User customer = customers.get(random.nextInt(customers.size()));
                User agent = agents.get(random.nextInt(agents.size()));
                User admin = admins.isEmpty() ? agents.get(0) : admins.get(0);
                
                // 计算时间
                Instant createdAt = now.plus(sampleData.createdDaysAgo, ChronoUnit.DAYS);
                Instant updatedAt = createdAt;
                Instant resolvedAt = null;
                Instant closedAt = null;
                
                // 对于已解决和已关闭的工单，设置解决时间和关闭时间
                if (sampleData.status == TicketStatus.RESOLVED && sampleData.resolvedDaysAgo != null) {
                    resolvedAt = now.plus(sampleData.resolvedDaysAgo, ChronoUnit.DAYS);
                    updatedAt = resolvedAt;
                }
                if (sampleData.status == TicketStatus.CLOSED && sampleData.closedDaysAgo != null) {
                    closedAt = now.plus(sampleData.closedDaysAgo, ChronoUnit.DAYS);
                    updatedAt = closedAt;
                } else if (sampleData.status == TicketStatus.CLOSED) {
                    closedAt = createdAt.plus(random.nextInt(5) + 1, ChronoUnit.DAYS);
                    updatedAt = closedAt;
                }
                
                // 设置负责人
                User assignedTo = null;
                if (sampleData.status != TicketStatus.OPEN) {
                    assignedTo = agent;
                }
                
                Ticket ticket = Ticket.builder()
                    .ticketNumber("TICKET-" + String.format("%06d", ++ticketCount))
                    .title(sampleData.title)
                    .description(sampleData.description)
                    .descriptionDetail("详细描述：" + sampleData.description + "\n\n这是自动生成的示例工单数据。")
                    .priority(sampleData.priority)
                    .status(sampleData.status)
                    .source(TicketSource.WEB)
                    .customer(customer)
                    .assignedTo(assignedTo)
                    .createdBy(customer)
                    .resolvedBy(sampleData.status == TicketStatus.RESOLVED ? agent : null)
                    .closedBy(sampleData.status == TicketStatus.CLOSED ? admin : null)
                    .createdAt(createdAt)
                    .updatedAt(updatedAt)
                    .resolvedAt(resolvedAt)
                    .closedAt(closedAt)
                    .estimatedHours(BigDecimal.valueOf(random.nextInt(10) + 1))
                    .actualHours(resolvedAt != null ? BigDecimal.valueOf(random.nextInt(8) + 1) : null)
                    .satisfactionScore(sampleData.status == TicketStatus.CLOSED ? random.nextInt(2) + 4 : null)
                    .isPublic(true)
                    .isEscalated(random.nextBoolean() && sampleData.priority == TicketPriority.URGENT)
                    .build();
                
                ticketRepository.save(ticket);
            }
            
            System.out.println("✅ 成功生成 " + ticketCount + " 个示例工单数据！");
        };
    }
    
    // 辅助类：示例工单数据
    private static class SampleTicketData {
        String title;
        String description;
        TicketStatus status;
        TicketPriority priority;
        int createdDaysAgo;  // 负数表示几天前创建
        Integer resolvedDaysAgo;  // 负数表示几天前解决
        Integer closedDaysAgo;    // 负数表示几天前关闭
        
        SampleTicketData(String title, String description, TicketStatus status, 
                        TicketPriority priority, int createdDaysAgo, int resolvedDaysAgo) {
            this(title, description, status, priority, createdDaysAgo, resolvedDaysAgo, null);
        }
        
        SampleTicketData(String title, String description, TicketStatus status, 
                        TicketPriority priority, int createdDaysAgo, int resolvedDaysAgo, Integer closedDaysAgo) {
            this.title = title;
            this.description = description;
            this.status = status;
            this.priority = priority;
            this.createdDaysAgo = createdDaysAgo;
            this.resolvedDaysAgo = resolvedDaysAgo;
            this.closedDaysAgo = closedDaysAgo;
        }
    }
}
